package com.bawei.module_moto_circle.ui.post.detail

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.RecycledViewPool
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.Success
import com.bawei.lib_common.base.state.UILoader
import com.bawei.lib_common.base.state.UIState
import com.bawei.lib_common.observeWithLifecycle
import com.bawei.lib_common.utils.ToastUtils
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_moto_circle.R
import com.bawei.module_moto_circle.databinding.ActivityPostDetailBinding
import com.bawei.module_moto_circle.databinding.LayoutPostDetailsContentBinding
import com.bawei.module_moto_circle.helper.LikeGifAnimHelper2
import com.bawei.module_moto_circle.model.CommentInfo
import com.bawei.module_moto_circle.ui.post.adapter.PostDetailsAdapter
import com.bawei.myclub.base.mvvm.view.BaseToolbarActivity
import dagger.hilt.android.AndroidEntryPoint

@Route(path = Router.Ui.PostDetailsActivity)
@AndroidEntryPoint
class PostDetailActivity : BaseToolbarActivity<PostDetailViewModel, ActivityPostDetailBinding>() {
    @Autowired
    @JvmField
    var postId: String = ""

    override val mLayoutResId: Int
        get() = R.layout.activity_post_detail

    override val mViewModel: PostDetailViewModel by viewModels()

    override val mPageCanBack: Boolean = false

    private lateinit var mUiLoader: UILoader

    private lateinit var mContentBinding: LayoutPostDetailsContentBinding

    //点击展开评论
    private val onClickShowAll: (CommentInfo, Int) -> Unit by lazy {
        { comments, position ->
            //mViewModel.handleShowAllComments(comments, position)
        }
    }

    private val mAdapter by lazy {
        PostDetailsAdapter(
            onClickLike = { postId, commentId, onPassed ->
                if (!AuthMMKV.hasLogin()) {
                    return@PostDetailsAdapter
                }
//                mViewModel.giveLike(postId, false, onPassed = {
//                    mViewModel.giveALikeForComment(postId, commentId) {
//                        onPassed?.invoke()
//                    }
//                })
            },
            clickShowAll = onClickShowAll,
            onClickRetry = {

            }
        )
    }

    //点赞gif动画
    val helper by lazy {
        LikeGifAnimHelper2(this)
    }

    //是否对帖子进行了修改
    private var mChangedSource: Boolean = false

    companion object {

        private var position: Int = 0
        private var toComment: Boolean = false
    }



    override fun initView() {
        super.initView()
        ARouter.getInstance().inject(this)
        initToolbar()
        if (postId.isEmpty()) {
            ToastUtils.showShort(this, "帖子信息为空")
            finish()
        }
        initUILoader()
        initAdapter()
    }

    private fun initUILoader() {
        mContentBinding = DataBindingUtil.inflate(
            LayoutInflater.from(this),
            R.layout.layout_post_details_content,
            null,
            false
        )

        mUiLoader = object : UILoader(this) {
            override fun loadSuccessView(container: ViewGroup?): View? {
                return mContentBinding.root
            }
        }.apply { updateState(UIState.LOADING) }

        mBinding.layoutContent.addView(mUiLoader)
    }

    private fun initAdapter() {
        mContentBinding.rvPostDetails.adapter = mAdapter
        mContentBinding.rvPostDetails.layoutManager = LinearLayoutManager(this)
        mContentBinding.rvPostDetails.setHasFixedSize(true)
        mContentBinding.rvPostDetails.setItemViewCacheSize(10)
        val pool = RecycledViewPool()
        pool.setMaxRecycledViews(0, 10)
        mContentBinding.rvPostDetails.setRecycledViewPool(pool)

    }

    override fun initData() {
        mContentBinding.viewModel = mViewModel
        mContentBinding.post = mViewModel.currentPost
        mViewModel.getPostById(postId)
    }

    override fun initListener() {
        //数据初始化状态
        mViewModel.mPostState.observeWithLifecycle(this) {
            when (it) {
                is Success -> {
                    updatePageData()
                }

                is Failed -> {
                    ToastUtils.showLong(this, it.message)
                    mUiLoader.updateState(UIState.EMPTY)
                }

                else ->{

                }
            }
        }
    }

    fun updatePageData() {
        val totalCommentsSize = mViewModel.currentPost?.comment_number ?: 0
        mContentBinding.lHeader.tvCommentsNum.text = String.format("%d 条评论", totalCommentsSize)
        mContentBinding.post = mViewModel.currentPost
        mAdapter.setPostInfo(
            mViewModel.currentPost,
            totalCommentsSize,
            mViewModel.get1stPageCommentsNum()
        )
        mAdapter.setCommentsNewData(mutableListOf<CommentInfo>().apply { addAll(mViewModel.formatCommentsList) })
        mUiLoader.updateState(UIState.SUCCESS)
    }


    private fun initToolbar() {
        mBinding.appbar.toolbarTitle.text =
            getString(com.bawei.lib_common.R.string.string_post_details)
        mToolbar.inflateMenu(R.menu.single_menu)
        mToolbar.setOnMenuItemClickListener {
            if (it.itemId == R.id.action) {
                if (!AuthMMKV.hasLogin()) {
                    return@setOnMenuItemClickListener true
                }

                // clickMoreAction()
//                clickMoreAction2()
            }
            true
        }
    }

}